import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:keyboard_avoider/keyboard_avoider.dart';
import '../model.dart';

class AddMood extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return AddMoodForm();
  }
}

class AddMoodForm extends StatefulWidget {
  @override
  AddMoodFormState createState() => AddMoodFormState();
}

class AddMoodFormState extends State<AddMoodForm> {
  TextEditingController _content = TextEditingController();
  final moodFormKey = GlobalKey<FormState>();
  String content;
  bool autovalidate = false;
  void submitMemoForm() {
    if (moodFormKey.currentState.validate()) {
      moodFormKey.currentState.save();
      this.fetchPosts(this._content.text);
      EasyLoading.show(
          status: 'loading...', maskType: EasyLoadingMaskType.black);
    } else {
      setState(() {
        autovalidate = true;
      });
    }
  }

  void submitRegisterForm() {
    if (moodFormKey.currentState.validate()) {
      moodFormKey.currentState.save();
      this.fetchPosts(content);
      EasyLoading.show(
          status: 'loading...', maskType: EasyLoadingMaskType.black);
    } else {
      setState(() {
        autovalidate = true;
      });
    }
  }

  String validateWebsite(value) {
    if (value.isEmpty) {
      return '网站名是必填项！';
    }
    return null;
  }

  String validateUsername(value) {
    if (value.isEmpty) {
      return '用户名是必填项！';
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        centerTitle: true,
        title: Text('新增想法'),
        elevation: 0.0,
        actions: <Widget>[
          ElevatedButton(
            style: ButtonStyle(
                // foregroundColor: Theme.of(context).accentColor, //字体颜色
                elevation: MaterialStateProperty.all(0)),
            child: Text('提交', style: TextStyle(color: Colors.white)),
            onPressed: this.submitMemoForm,
          ),
        ],
      ),
      body: Theme(
        data: Theme.of(context).copyWith(
          primaryColor: Colors.black,
        ),
        child: Container(
            decoration: new BoxDecoration(
              color: Colors.blue[50],
            ),
            child: KeyboardAvoider(
              autoScroll: true,
              child: Column(
                  // mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Form(
                        key: moodFormKey,
                        child: Container(
                          child: new ConstrainedBox(
                            constraints:
                                BoxConstraints(maxHeight: double.infinity),
                            child: TextField(
                              keyboardType: TextInputType.multiline,
                              strutStyle: StrutStyle(height: 1.86),
                              minLines: 15,
                              maxLines: null,
                              decoration: InputDecoration(
                                  contentPadding: EdgeInsets.all(16.0),
                                  fillColor: Colors.blue[50],
                                  filled: true,
                                  isCollapsed: true,
                                  // labelText: '请输入便签内容',
                                  // helperText: '请输入便签内容',
                                  border: InputBorder.none),
                              controller: _content,
                              onSubmitted: (value) {
                                this.setState(() {
                                  this._content.text = value;
                                });
                              },
                            ),
                          ),
                        ))
                  ]),
            )),
      ),
    );
  }

  Future fetchPosts($content) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var dataBody = jsonEncode({'content': $content});
    print(dataBody);
    final response = await http.post(
        'https://me.yuanqiao.pw/api/me/insertMemo.php',
        body: dataBody,
        headers: {HttpHeaders.authorizationHeader: prefs.get('user_token')});
    EasyLoading.dismiss();
    if (response.statusCode == 200) {
      final responseBody = json.decode(response.body);
      print('responseBody');
      print(responseBody);
      Fluttertoast.showToast(
          msg: responseBody['error'],
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.white,
          textColor: Colors.black87,
          fontSize: 16.0);
      Navigator.of(context).pushNamed('/home', arguments: ScreenArguments(3));
    } else {
      Fluttertoast.showToast(
          msg: '网络或服务器错误',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.white,
          textColor: Colors.black87,
          fontSize: 16.0);
    }
  }
}
